struct ListNode {
  int val;
  ListNode *next;
  ListNode(int x) : val(x), next(nullptr) {}
};

class Solution {
public:
  ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
    ListNode *aPtr = headA, *bPtr = headB;
    while (aPtr != bPtr) {
      if (aPtr == nullptr) {
        aPtr = headB;
      } else {
        aPtr = aPtr->next;
      }

      if (bPtr == nullptr) {
        bPtr = headA;
      } else {
        bPtr = bPtr->next;
      }
    }
    return aPtr;
  }
};
